package org.example.guava;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.concurrent.ExecutionException;

/**
 * @Classname Test1
 * @Description LoadingCache 多线程demo
 * @Date 2020/12/21 11:50 上午
 * @Created by xiangjd
 */
public class Test1 {


    private static CacheLoader<String, String> loader = new CacheLoader<String, String>() {
        @Override
        public String load(String key) throws Exception {
            Thread.sleep(1000); //休眠1s，模拟加载数据
            System.out.println(key + " is loaded from a cacheLoader!");
            return key + "is value";
        }
    };

    private static LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder()
            .maximumSize(3)
            .build(loader);//在构建时指定自动加载器

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thead1");
                try {
                    System.out.println("load1");
                    loadingCache.get("key1");

                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread2");
                try {
                    System.out.println("load2");
                    loadingCache.get("key1");
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
